package cn.jiyun.filer;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 季乾帅
 * @create 2023/8/22 10:50
 */
@Component
@Slf4j
public class MyFiler implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //自定义路径
        String loginUrl = "/con/login";
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取URL路径
        String path = request.getURI().getPath();
        log.info("本次访问的路径 : {}",path);
        if (path.contains("Cons")) {
            return chain.filter(exchange);
        }
        if (path.contains("type")) {
            return chain.filter(exchange);
        }
        if (path.contains("catalog")) {
            return chain.filter(exchange);
        }

        if (path.contains("course")) {
            return chain.filter(exchange);
        }
        if (path.contains(loginUrl)) {
            //包含说明是登陆页面 放行
            return chain.filter(exchange);

        } else {
            //获取token
            String token = getToken(request);
            if (StringUtils.isNotBlank(token)) {
                try {
                    //检查token
                    boolean verify = JWTUtil.verify(token, "1".getBytes());
                    if (verify) {
                        return chain.filter(exchange);
                    } else {
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }
                } catch (Exception e) {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            } else {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }

    public String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("token");
        log.info("token:{}",token);
        return token;
    }
}
